import 'dart:io';

import 'package:flutter/material.dart';
import 'package:qr_code_app/common/constant/color_config.dart';
import 'package:qr_code_app/common/util/util.dart';
import 'package:qr_code_app/generated/assets/qr_code_app_assets.dart';
import 'package:qr_code_app/module/diary/bloc/log_bloc.dart';
import 'package:qr_code_app/widget/common_app_bar.dart';
import 'package:todo_flutter/todo_flutter.dart';

class PublishLogPage extends StatefulWidget {
  const PublishLogPage({Key? key}) : super(key: key);

  @override
  _PublishLogPageState createState() => _PublishLogPageState();
}

class _PublishLogPageState extends BaseState<PublishLogPage> {
  final DataChangeBloc<File?> selectedMemoryBloc = DataChangeBloc(null);

  final controller = TextEditingController();

  LogBloc get bloc => getBloc<LogBloc>();

  @override
  void initState() {
    super.initState();
    addBloc(LogBloc());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonAppBar(
        '发布',
        showBack: true,
        menu: '保存',
        onMenuTap: () async {
          var file;
          if (ObjectUtil.isEmpty(selectedMemoryBloc.state)) {
            file = await Util().getFileFromAsset(QrCodeAppAssets.defaultImage);
          } else {
            file = selectedMemoryBloc.state!;
          }
          await bloc.addPost(file, controller.value.text ?? '');
          RouterUtil.instance.pop();
        },
      ),
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        padding: symmetric(horizontal: 16),
        child: Column(
          children: [
            _content(),
            SizedBox(height: 20),
            _userH(),
          ],
        ),
      ),
    );
  }

  Widget _userH() {
    return CommonClickWidget(
      singleClick: () {
        Util().selectImg(context).then(selectedMemoryBloc.changeData);
      },
      child: DataChangeWidget(
          bloc: selectedMemoryBloc,
          child: (c, s) {
            if (ObjectUtil.isNotEmpty(s)) {
              return CommonImage(
                file: s,
                size: 300,
                borderRadius: BorderRadius.circular(12),
              );
            } else {
              return CommonImage(
                asset: QrCodeAppAssets.defaultImage,
                size: 300,
                borderRadius: BorderRadius.circular(12),
              );
            }
          }),
    );
  }

  Widget _content() {
    return CommonInputArea(
      controller: controller,
      placeholder: '输入心情/描述\n\n\n\n\n\n\n\n\n',
      fontSize: 16,
      color: ColorsConfig.ff161619,
      maxLines: 10,
    );
  }
}
